$(function () {
    //初始化工作台
    initBacklog();

    $('body').on('click', 'article[data-upload]', function () { // 课程 -- 章节上传
        var courseId = $(this).data('upload');
        getRedirectMenu(baseloaction + '/admin/course/catalog/initCourseCatalog?courseId=' + courseId);
    }).on('click', 'div[data-record]', function () { // 考试 -- 阅卷
        var recordId = $(this).data('record');//记录ID
        var type = $(this).data('type');
        var url = '/admin/exam/record/markUserExamRecord?examRecordId=' + recordId;
        if (type == 2) {
            url = "/admin/exam/record/markUserTaskRecord?examRecordId=" + recordId;
        }
        getRedirectMenu(baseloaction + url);
    }).on('click', 'div[data-agent]', function () {
        var agent = $(this).data('agent');
        parent.layer.open({
            type: 2,
            title: '<strong>审核</strong>',
            shadeClose: false,
            shade: [0.3, '#000000'],
            content: baseloaction + '/admin/agent/user/initAduit?agentUserId=' + agent,
            area: winArea,
            btn: ['关闭'],
            end: function () {
                initBacklog();
            }
        });

    }).on('click', 'div[data-question]', function () { //问题 - 回答 questionId
        var questionId = $(this).data('question');
        var isFree = $(this).data('isfree');
        var url = "/admin/qa/question/freeQuestionInfo?questionId=" + questionId;
        if (isFree == 2) {
            url = "/admin/qa/question/noFreeQuestionInfo?questionId=" + questionId;
        }
        openWindow("学员问题", url);
    });


    $.ajax({
        url: baseloaction + "/admin/manage/work//getBacklogCount?isLive=false",
        dataType: 'json',
        success: function (result) {
            if (result.success == true) {
                if (result.entity > 0) {
                    $("#prompt").removeClass("hide");
                }
            }


        }
    });

    function initBacklog() {
        $.ajax({
            url: baseloaction + '/admin/manage/work/ajaxBacklogList',
            type: 'post',
            success: function (html) {
                $('#workbench-backlog').html(html);
                //  getLiveList(1);

                var calendarEl = document.getElementById('live-log-list');
                var calendar = new FullCalendar.Calendar(calendarEl, {
                    header: {
                        left: 'prev,next today',
                        center: 'title',
                        right: 'dayGridMonth,timeGridWeek,timeGrid'
                    },
                    plugins: ['dayGrid', 'timeGrid'],
                    locale: 'zh-cn',
                    defaultView: 'timeGridWeek',
                    events: baseloaction + '/admin/manage/work/ajaxBacklogLiveList',
                    eventClick: function (info) {
                        openUser(info.event.extendedProps);
                    }
                });

                calendar.render();
            },
            complete: function () {
                $('#workbench-backlog div.icLoading').remove();
            },
            error: function () {
                icModale(0, '系统错误，数据加载失败');
            }
        });
    }

    function clientTips() {
        setButtonInfo();
        var _ele = $('#sysItemLiveEle').html();
        parent.layer.open({
            type: 1,
            area: ['450px', '210px'],
            skin: 'layui-layer-demo',
            title: '讲师进入直播',
            content: _ele,
            success: function (a) {
                a.find('.download').click(function () {
                    var platform = (navigator.platform || '').toLowerCase();
                    if (platform.indexOf('win') != -1) {
                        window.open('https://c1.96koo.net/package/zhinengzhibo6.9.0.zip', "_blank");
                    } else if (platform.indexOf('mac') != -1) {
                        window.open('https://c1.96koo.net/package/zhinengzhibomac6.9.2.dmg', "_blank");
                    }
                });
            }
        });
    }


    /**
     * 获取短信消费记录
     * @param pageNo 当前页码
     */
    function getLiveList(pageNo) {
        var params = {};
        params = JSON.stringify(params);
        var obj = {
            url: baseloaction + '/admin/manage/work/ajaxBacklogLiveList',//请求URL
            contextId: 'live-log-list',//响应内容页面设置内容ID
            params: params,//请求参数
            pageNo: pageNo,//页码
            selectAllId: '11', //全选框ID
            pageCall: getLiveList, //分页回调加载数据(点击上下页时调用,该方法也在加载页面完成时调用)
            callback: function () {//数据加载完成回调

            }
        };
        ajaxGetListData(obj);
    }


    /**
     * 进入直播间
     *
     * @param auth_id
     * @param auth_password
     * @param roomId
     * @param sign
     * @param teacherName
     * @param type
     */
    function enterLiveRoom(auth_id, auth_password, roomId, sign, teacherName, role, type) {
        var url = 'http://admin.96koo.net/common/room/ClientIntoRoom?identity_id=' + auth_id + '&identity_pwd=' + auth_password + '&room_id=' + roomId + '&user_number=' + sign + '&user_role=' + role + '&user_name=' + teacherName;
        $.ajax({
            url: url,
            dataType: 'json',
            success: function (result) {
                var enterClassroomClientURL = result.data;
                var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
                if (userAgent.indexOf("Firefox") > -1 || (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !userAgent.indexOf("Opera") > -1)) {
                    // IE 和火狐用 window.open 打开
                    var client = window.open(enterClassroomClientURL);
                    setTimeout(function () {
                        if (client) {
                            client.close(); //关闭新打开的浏览器窗口，避免留下一个 空白窗口
                        }
                    }, 5000);
                } else {
                    var startTime = Date.now();
                    var ifr = document.createElement('iframe');
                    ifr.src = enterClassroomClientURL;
                    ifr.style.display = 'none';
                    document.body.appendChild(ifr);
                    var t = window.setTimeout(function () {
                        var endTime = Date.now();
                        if (!startTime || endTime - startTime < 800) {
                            clientTips();
                        }
                    }, 1200);
                    window.onblur = function () {
                        window.clearTimeout(t);
                    }
                }
            }
        });
    }

    function setButtonInfo() {
        var platform = (navigator.platform || '').toLowerCase();
        if (platform.indexOf('win') != -1) {
            $('.download').data('link', 'https://c1.96koo.net/package/zhinengzhibo6.8.0.zip').html('windows客户端下载');
        } else if (platform.indexOf('mac') != -1) {
            $('.download').data('link', 'https://c1.96koo.net/package/zhinengzhibomac6.8.0.dmg').html('mac客户端下载');
        }
    }

    function openWindow(title, url) {
        parent.layer.open({
            type: 2,
            area: winArea,
            content: baseloaction + url,
            maxmin: true,
            shade: [0.3, '#000'],
            shadeClose: false,
            title: title
        });
    }

    function openUser(that) {
        var playUrl = that.playUrl;
        var id = that.materialId;
        var configType = sysVideoConfig['contextTreeMap']['type'];
        var teacherName = that.name;
        var teacherCode = that.teacherCode;
        var admincode = that.adminCode;
        var ptcode = that.ptcode;
        var liveBillingType = that.livebilling;
        if (!that.isOpenClient && that.liveState != 2) {
            if (that.liveState == 3) {
                icModale(0, '直播未开始');
            } else if (that.liveState == 1) {
                icModale(0, '直播已结束');
            }
            return;
        }
        if (that.type == 'CC') {
            //今日直播调起选择直播身份和下载直播客户端
            liverOpenOptionsFnByCC(playUrl, teacherName, teacherCode, admincode, ptcode, liveBillingType);
        } else if(that.type == 'TT'){
            liverOpenOptionsFnByTT(id);
        }
    }


    //今日直播调起选择直播身份和下载直播客户端
    function liverOpenOptionsFnByCC(playUrl, teacherName, teacherCode, admincode, ptcode, liveBillingType) {
        var _ele = $('#sysItemLiveTipsEleByCC').val()
        parent.layer.open({
            type: 1,
            area: ['860px', '600px'],
            content: _ele,
            shade: [0.3, '#000'],
            shadeClose: false,
            title: '今日直播',
            success: function (layero, index) {
                layero.find('[data-toggle="tooltip"]').tooltip();
                layero.find("#theHostLive").on("click", function () {
                    openInputName(1, playUrl, teacherName, teacherCode, admincode, ptcode, liveBillingType);
                });
                layero.find("#theTeacherLive").on("click", function () {
                    openInputName(2, playUrl, teacherName, teacherCode, admincode, ptcode, liveBillingType);
                });
                layero.find("#theTaLive").on("click", function () {
                    openInputName(3, playUrl, teacherName, teacherCode, admincode, ptcode, liveBillingType);
                });
            }
        });
    }

    function openInputName(type, roomid, teacherName, teacherCode, admincode, ptcode, liveBillingType) {
        var _ele = $('#openInputName').val()
        var liveId = sysVideoConfig['contextTreeMap']['ccAppId'];

        parent.layer.open({
            type: 1,
            area: ['240px', '180px'],
            skin: 'layui-layer-demo',
            title: '<strong>请输入姓名</strong>',
            content: _ele,
            btn: '确定',
            yes: function (index, layero) {
                var pass = layero.find('#rejectedCause').val();
                if (pass.length <= 0) {
                    icModale(0, '请填写姓名');
                    return;
                }
                if (pass.length >= 30) {
                    icModale(0, '姓名不能大于30个字符');
                    return;
                }
                icModale(0, '进入中');

                if (type == 1) {
                    var url = "https://view.csslcloud.net/api/view/index?roomid=" + roomid + "&userid=" + liveId + "&autoLogin=true&viewername=" + pass + "&autoLogin=true&viewertoken=" + ptcode;
                    window.open(url, "_blank");
                }
                if (type == 2) {
                    if (liveBillingType == 1) {//小班课
                        var url = "https://class.csslcloud.net/index/presenter/?roomid=" + roomid + "&userid=" + liveId + "&username=" + pass + "&password=" + teacherCode + "&autoLogin=true";
                        window.open(url, "_blank");
                    } else {
                        window.location.href = "cclive://" + liveId.trim() + "/" + roomid + "/" + pass.trim() + "/" + teacherCode;
                    }
                    // window.location.href ="https://livec2.96koo.net/api/newindex/presenter/"+liveId+"/"+roomid+"/"+pass+"/"+teacherCode;

                }

                if (type == 3) {
                    var url = "https://view.csslcloud.net/api/view/assistant?viewername=" + pass + "&roomid=" + roomid + "&userid=" + liveId + "&autoLogin=true&viewertoken=" + admincode;
                    window.open(url, "_blank")
                }

                icModale(0, '进入中');
                parent.layer.closeAll();

            }
        });

    }

    function liverOpenOptionsFnByTT(id) {
        var _ele = $('#sysItemLiveTipsEleByTT').val()
        parent.layer.open({
            type: 1,
            area: ['860px', '600px'],
            content: _ele,
            shade: [0.3, '#000'],
            shadeClose: false,
            title: '今日直播',
            success: function (layero, index) {
                layero.find('[data-toggle="tooltip"]').tooltip();
                layero.find("#theTeacherLiveClient").on("click", function () {
                    openInputNameByTT(1,id,1);
                });
                layero.find("#theTeacherLiveWebPage").on("click", function () {
                    openInputNameByTT(1,id,2);
                });
                layero.find("#theTaLiveClient").on("click", function () {
                    openInputNameByTT(2, id,1);
                });
                layero.find("#theTaLiveWebPage").on("click", function () {
                    openInputNameByTT(2,id,2);
                });
                layero.find("#theHostLiveClient").on("click", function () {
                    openInputNameByTT(3,id,1);
                });
                layero.find("#theHostLiveWebPage").on("click", function () {
                    openInputNameByTT(3,id,2);
                });
            }
        });
    }

    function openInputNameByTT(type, id, openType) {
        parent.layer.closeAll();
        if (openType == '1') {
            parent.layer.open({
                content: '进入前需安装直播客户端，如已安装可点击进入即可！'
                ,title: '友情提示'
                , btn: ['进入直播间', '下载客户端']
                , yes: function (index, layero) {
                    toLive(type,id, openType)
                }, btn2: function (index, layero) {
                    window.location.href = "https://ftp.3ttech.cn/云中课堂.exe";
                }, cancel: function () {
                }
            });
        } else {
            toLive(type,id, openType);
        }
    }

    function toLive(type,id,openType) {
        var liveUrl = "";
        var _ele = $('#openInputName').val()
        if (type != 3) {
            parent.layer.closeAll();
            $.ajax({
                url: baseloaction + '/admin/liveToV/create/getLiveParam',
                data: {'couMaterialId': id, 'type': type, 'selectType': 'indexLive'},
                dataType: 'json',
                success: function (result) {
                    if (result.success == true) {
                        if (openType == '1') {
                            liveUrl = "yzkt://quickenterlive&i=" + result.entity.UID + "&k=" + result.entity.safeKey + "&t=" + result.entity.timeStamp + "&r=" + result.entity.classId + "";
                            window.protocolCheck(
                                liveUrl,
                                function () {
                                    icModale(0, "客户端软件未安装");
                                }
                            );
                            event.preventDefault ? event.preventDefault() : event.returnValue = false;
                        } else {
                            var url = result.entity.classRoomUrl;
                            $("#url").val(url);
                            $("#toLiveIframe").submit();
                        }
                    } else {
                        icModale(0, result.message);
                    }
                }
            });
        } else {
            var html = '请输入账号';
            parent.layer.open({
                type: 1,
                area: ['240px', '180px'],
                skin: 'layui-layer-demo',
                title: '<strong>'+html+'</strong>',
                content: _ele,
                btn: '确定',
                yes: function (index, layero) {
                    var pass = layero.find('#rejectedCause').val();
                    if (pass.length <= 0) {
                        icModale(0, html);
                        return;
                    }
                    if (pass.length >= 30) {
                        icModale(0, '大于30个字符');
                        return;
                    }
                    icModale(0, '进入中');
                    $.ajax({
                        url: baseloaction + '/admin/liveToV/create/getLiveParam',
                        data: {
                            'couMaterialId': id,
                            'type': type,
                            'name': pass,
                            'selectType': 'indexLive'
                        },
                        dataType: 'json',
                        success: function (result) {
                            parent.layer.closeAll();
                            if (result.success == true) {
                                if (openType == '1') {
                                    liveUrl = "yzkt://quickenterlive&i=" + result.entity.UID + "&k=" + result.entity.safeKey + "&t=" + result.entity.timeStamp + "&r=" + result.entity.classId + "";
                                    window.protocolCheck(
                                        liveUrl,
                                        function () {
                                            icModale(0, "客户端软件未安装");
                                        }
                                    );
                                    event.preventDefault ? event.preventDefault() : event.returnValue = false;
                                } else {
                                    var url = result.entity.classRoomUrl;
                                    $("#url").val(url);
                                    $("#toLiveIframe").submit();
                                    parent.layer.closeAll();
                                }
                            } else {
                                icModale(0, result.message);
                            }
                        }
                    });
                }
            });
        }
    }
});